import React, { useState, useEffect, useRef, ReactText } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { getUserList, userDelete, resetPwd } from '@/services/system/user';
import { getDictList4Type } from '@/services/system/dict';
import UserAdd from '@/pages/system/user/components/UserAdd';
import { Tag, Popconfirm, Button, message, Spin } from 'antd';
import UserPhotoView from '@/pages/common/UserPhotoView';
import { DeleteOutlined, KeyOutlined } from '@ant-design/icons';
import UserEdit from '@/pages/system/user/components/UserEdit';

const { CheckableTag } = Tag;

/**
 * 用户列表
 *
 * @author zhangby
 * @date 21/9/20 5:02 pm
 */
export default (): React.ReactNode => {
  const ref = useRef<ActionType>();
  const [rows, setRows] = useState<ReactText[]>([]);
  const [loading, setLoading] = useState(false);
  const [userType, setUserType] = useState<any>({});

  // 初始化
  useEffect(() => {
    try {
      // 查询角色类型
      getDictList4Type('user_type').then((res) => {
        if (res.code === '000') {
          const userTypeJson = {};
          res.result.forEach((item) => {
            userTypeJson[item.value] = { text: item.label };
          });
          setUserType(userTypeJson);
        }
      });
    } catch (e) {
      setLoading(false);
    }
  }, []);

  // 删除
  const onDelete = async (id: string) => {
    try {
      setLoading(true);
      await userDelete(id);
      setLoading(false);
      message.success('删除记录成功');
      // @ts-ignore
      ref.current?.reloadAndRest();
    } catch (e) {
      setLoading(false);
    }
  };

  // 批量删除
  const onBatchDelete = () => {
    if (rows.length === 0) {
      message.error('请选择要操作的记录');
      return;
    }
    onDelete(rows.join(','));
  };

  // 重置密码
  const onResetPwd = async () => {
    try {
      if (rows.length === 0) {
        message.error('请选择要操作的记录');
        return;
      }
      setLoading(true);
      const data = await resetPwd(rows.join(','));
      if (data.code === '000') {
        message.success('密码重置成功');
        ref.current?.clearSelected();
      }
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };

  // @ts-ignore
  return (
    <>
      <PageContainer
        subTitle="系统用户管理"
        extra={[
          <span key="pwd">
            {rows.length > 0 ? (
              <Popconfirm
                title="确定要重置密码吗?"
                onConfirm={onResetPwd}
                okText="Yes"
                cancelText="No"
              >
                <Button type="primary" ghost>
                  <KeyOutlined />
                  重置密码
                </Button>
              </Popconfirm>
            ) : null}
          </span>,
          <span key="del">
            {rows.length > 0 ? (
              <Popconfirm
                title="确定要删除选中的记录吗?"
                onConfirm={onBatchDelete}
                okText="Yes"
                cancelText="No"
              >
                <Button type="primary" danger>
                  <DeleteOutlined />
                  批量删除
                </Button>
              </Popconfirm>
            ) : null}
          </span>,
          <UserAdd key="add" refresh={ref.current?.reload} />,
        ]}
      >
        <Spin spinning={loading}>
          <ProTable<System.SysUser>
            actionRef={ref}
            scroll={{ x: 900 }}
            columns={[
              {
                title: '头像',
                dataIndex: 'name',
                width: 80,
                hideInSearch: true,
                align: 'center',
                render: (_, record) => <UserPhotoView size={35} photoStr={record.photo} />,
              },
              {
                title: '用户名',
                dataIndex: 'name',
                width: 100,
                render: (item, _) => <CheckableTag style={{ padding: 0 }}>{item}</CheckableTag>,
              },
              {
                title: '登录名',
                dataIndex: 'loginName',
                width: 100,
                render: (item, record) => (
                  <UserEdit userId={record.id} refresh={ref.current?.reload}>
                    <Button type="link" style={{ padding: 0, margin: 0 }}>
                      {item}
                    </Button>
                  </UserEdit>
                ),
              },
              {
                title: '用户类型',
                dataIndex: 'userType',
                width: 120,
                valueEnum: userType,
                render: (_, record) => (
                  <Tag color={roleColors[record.userType % 5]}>{record.tails.userTypeLabel}</Tag>
                ),
              },
              {
                title: '联系方式',
                dataIndex: 'mobile',
                width: 120,
                render: (item, _) => <CheckableTag style={{ padding: 0 }}>{item}</CheckableTag>,
              },
              {
                title: '电子邮箱',
                dataIndex: 'email',
                width: 120,
                render: (item, _) => <CheckableTag style={{ padding: 0 }}>{item}</CheckableTag>,
              },
              {
                title: '创建时间',
                dataIndex: 'createDate',
                width: 120,
                hideInSearch: true,
                render: (item, _) => <CheckableTag style={{ padding: 0 }}>{item}</CheckableTag>,
              },
              {
                title: '操作',
                dataIndex: 'option',
                valueType: 'option',
                align: 'center',
                width: 150,
                render: (_, record) => (
                  <>
                    <UserEdit userId={record.id} refresh={ref.current?.reload} />
                    <Popconfirm
                      placement="topRight"
                      title="确定要删除选中的记录吗?"
                      onConfirm={() => onDelete(record.id)}
                      okText="Yes"
                      cancelText="No"
                    >
                      <Button type="primary" shape="circle" danger style={{ marginLeft: 10 }}>
                        <DeleteOutlined />
                      </Button>
                    </Popconfirm>
                  </>
                ),
              },
            ]}
            rowSelection={{
              columnWidth: 20,
              onChange: (selectedRowKeys, _) => setRows(selectedRowKeys),
            }}
            request={(params, sorter, filter) => getUserList({ ...params, sorter, filter })}
            pagination={{
              pageSize: 10,
            }}
            rowKey="id"
            headerTitle="用户列表"
          />
        </Spin>
      </PageContainer>
    </>
  );
};

const roleColors = ['red', 'cyan', 'green', 'blue', 'geekblue'];
